import * as React from 'react';
import { Col, DatePicker } from 'antd';
import * as moment from 'moment';
interface Props extends React.Props<any> {
  label?: string;
  value?: any;
  defaultValue?: [string, string];
  error?: string;
  col?: number;
  disabled?: boolean;
  required?: boolean;
  modelKey: string;
  dateFormat: string;
  placeholder?: [string, string];
  onChange?: (e: string, key: string) => void;
}
export class SRangePicker extends React.PureComponent<Props, any> {
  static defaultProps = {
    dateFormat: 'YYYY-MM-DD'
  }
  constructor(props) {
    super(props);
    this.state = {
      startTime: props.defaultValue && props.defaultValue[0] ? moment(props.defaultValue[0], props.dateFormat) : null,
      endTime:   props.defaultValue && props.defaultValue[1] ? moment(props.defaultValue[1], props.dateFormat) : null,
    }
  }
  componentDidMount = () => {
    const { defaultValue, modelKey} = this.props;
    if (defaultValue && defaultValue.length) {
      this.props.onChange!(defaultValue.join('~'), modelKey);
    }
  }
  datePickerChange(e) {
    if (e.length) {
      const { modelKey, dateFormat } = this.props;
      const date: string = e.map(v => moment(v).format(dateFormat)).join('~');
      this.props.onChange!(date, modelKey);
    }
  }
  render() {
    const { startTime, endTime } = this.state;
    const { label, col, disabled, required, error, placeholder } = this.props;
    return (
      <div className='s-datePicker smart-form'>
        <Col span={col}>
          {
            label ?
            <label className='label'>
              <span>{label}</span>
              {required ? <i className='required'>*</i> : null}
            </label> : null
          }
          <div className={error ? 'form-error' : ''}>
            <DatePicker.RangePicker
              disabled={disabled}
              style={{width: '100%'}}
              placeholder={placeholder}
              defaultValue={[startTime, endTime]}
              onChange={e => this.datePickerChange(e)}
            />
          </div>
          <em className='note-error'>{error}</em>
        </Col>
      </div>
    )
  }
}